package com.eestimate.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.activation.DataHandler;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;

import com.eestimate.exceptions.ErrorCodeEnum;
import com.eestimate.exceptions.ServiceException;

public class FileUploadUtils {
	
	
	public void uploadFile(List<Attachment> attachments) throws ServiceException{
		
		for (Attachment attachment : attachments) {
	         
			DataHandler handler = attachment.getDataHandler();
	         
			try {
				
				InputStream stream = handler.getInputStream();
	            MultivaluedMap<String, String> map = attachment.getHeaders();
	            System.out.println("fileName: " + getFileName(map));
	            File uploadDir = new File(PropertiesUtils.getInstance().getProperty(Constants.KEY_FILE_UPLOAD_PATH));
	            if(!uploadDir.exists()){
	            	uploadDir.mkdir();
	            }
	            OutputStream out = new FileOutputStream(new File(uploadDir.getAbsolutePath()+"/"+ getFileName(map)));

	            int read = 0;
	            byte[] bytes = new byte[1024];
	            while ((read = stream.read(bytes)) != -1) {
	               out.write(bytes, 0, read);
	            
	            }
	            stream.close();
	            out.flush();
	            out.close();
	         
			} catch (Exception exc) {
	            exc.printStackTrace();
	            throw new ServiceException(exc.getMessage(), exc, ErrorCodeEnum.INTERNAL_SERVER_ERROR);
			}
		}
		
	}
	
	private String getFileName(MultivaluedMap<String, String> header) {
	      String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
	      for (String filename : contentDisposition) {
	         if ((filename.trim().startsWith("filename"))) {
	            String[] name = filename.split("=");
	            String exactFileName = name[1].trim().replaceAll("\"", "");
	            return exactFileName;
	         }
	      }
	      return "unknown";
	}

}
